import os
import asyncio

from dotenv import load_dotenv
from neo4j._optional_deps import np

from lightrag import LightRAG, QueryParam
from lightrag.llm.ollama import ollama_embed
from lightrag.llm.openai import openai_complete_if_cache, openai_embed
from lightrag.utils import EmbeddingFunc
from lightrag.kg.shared_storage import initialize_pipeline_status

# 新增：加载 .env 文件中的环境变量
load_dotenv()

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
WORKING_DIR = os.path.join(ROOT_DIR, "myKG")
if not os.path.exists(WORKING_DIR):
    os.mkdir(WORKING_DIR)

print(f"WorkingDir: {WORKING_DIR}")

# redis
os.environ["REDIS_URI"] = "redis://localhost:6379"
# neo4j
BATCH_SIZE_NODES = 500
BATCH_SIZE_EDGES = 100
# os.environ["NEO4J_URI"] = "bolt://117.50.173.35:7687"
# os.environ["NEO4J_USERNAME"] = "neo4j"
# os.environ["NEO4J_PASSWORD"] = "12345678"

# milvus
os.environ["MILVUS_URI"] = "http://117.50.173.35:19530"
os.environ["MILVUS_USER"] = "root"
os.environ["MILVUS_PASSWORD"] = "Milvus"
os.environ["MILVUS_DB_NAME"] = "lightrag"


async def llm_model_func(
        prompt, system_prompt=None, history_messages=[], keyword_extraction=False, **kwargs
) -> str:
    # 使用 openai_complete_if_cache 函数调用大语言模型（如果有缓存，则使用缓存）
    return await openai_complete_if_cache(
        os.getenv("LLM_MODEL"),  # 从环境变量中获取 LLM 模型的名称
        prompt,  # 输入提示（prompt）
        system_prompt=system_prompt,  # 系统提示（可选）
        history_messages=history_messages,  # 历史消息，用于上下文
        api_key=os.getenv("LLM_BINDING_API_KEY"),  # 从环境变量中获取 LLM API 密钥
        base_url=os.getenv("LLM_BINDING_HOST"),  # 从环境变量中获取 LLM API 基础 URL
        **kwargs,  # 其他参数
    )


async def embedding_func(texts: list[str]) -> np.ndarray:
    return await openai_embed(
        texts,
        model=os.getenv("EMBEDDING_MODEL"),  # 从环境变量中获取嵌入模型的名称
        api_key=os.getenv("EMBEDDING_BINDING_API_KEY"),  # 从环境变量中获取嵌入模型的 API 密钥
        base_url=os.getenv("EMBEDDING_BINDING_HOST"),  # 从环境变量中获取嵌入模型的 API 基础 URL

    )


async def initialize_rag():
    rag = LightRAG(
        working_dir=WORKING_DIR,
        llm_model_func=llm_model_func,
        llm_model_max_token_size=32768,
        embedding_func=embedding_func,
        chunk_token_size=512,
        chunk_overlap_token_size=256,
        kv_storage="RedisKVStorage",
        graph_storage="Neo4JStorage",
        vector_storage="MilvusVectorDBStorage",
        doc_status_storage="RedisKVStorage",
    )

    await rag.initialize_storages()
    await initialize_pipeline_status()

    return rag


async def main():
    # Initialize RAG instance
    rag = await asyncio.run(initialize_rag())
    #
    # with open("./book.txt", "r", encoding="utf-8") as f:
    #     rag.insert(f.read())
    #
    # # Perform naive search
    # print(
    #     rag.query(
    #         "What are the top themes in this story?", param=QueryParam(mode="naive")
    #     )
    # )
    #
    # # Perform local search
    # print(
    #     rag.query(
    #         "What are the top themes in this story?", param=QueryParam(mode="local")
    #     )
    # )
    #
    # # Perform global search
    # print(
    #     rag.query(
    #         "What are the top themes in this story?", param=QueryParam(mode="global")
    #     )
    # )
    #
    # # Perform hybrid search
    # print(
    #     rag.query(
    #         "What are the top themes in this story?", param=QueryParam(mode="hybrid")
    #     )
    # )


if __name__ == "__main__":
    asyncio.run(main())
